package nil.ed.simulator.request.client.activity;

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;

import java.util.Map;

/**
 * Http活动.
 * @author lidelin.
 */
public abstract class AbstractHttpActivity implements IActivity {

    @Override
    public boolean process(Map<String, Object> attrMap) {
        try {
            HttpUriRequest request = getRequest(attrMap);
            if (request == null) {
                return false;
            }
            HttpClient httpClient = getHttpClient(attrMap);
            CookieStore cookieStore = getCookieStore(attrMap);
            HttpResponse response = httpClient.execute(request);
            if (response.getStatusLine().getStatusCode() != 200) {
                return false;
            }
            for (Cookie cookie : cookieStore.getCookies()) {
                attrMap.put("cookie_" + cookie.getName(), cookie.getValue());
            }
            return doFinalProcess(response, attrMap);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取Http请求.
     * @return Http请求.
     */
    protected abstract HttpUriRequest getRequest(Map<String, Object> attrMap);

    /**
     * 获取HttpClient.
     * @param attrMap HttpClient.
     * @return HttpClient.
     */
    protected HttpClient getHttpClient(Map<String, Object> attrMap) {
        return (HttpClient) attrMap.get(BuiltInAttrs.HTTP_CLIENT_ATTR);
    }

    /**
     * 获取CookieStore.
     * @param attrMap CookieStore.
     * @return CookieStore.
     */
    protected CookieStore getCookieStore(Map<String, Object> attrMap) {
        return (CookieStore) attrMap.get(BuiltInAttrs.COOKIE_STORE_ATTR);
    }

    /**
     * 最终处理.
     * @param response      响应结果
     * @param customAttrMap 自定义参数.
     */
    protected boolean doFinalProcess(HttpResponse response,
                                           Map<String, Object> customAttrMap) {
        return true;
    }

}
